package com.szxy.casdemo;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: zwz
 * @Date:2020/10/23 16:23
 * @Description: ABA 问题
 **/
public class ABADemo {
    private static AtomicReference<Integer> atomicReference = new AtomicReference<Integer>(100);

    public static void main(String[] args) {
        new Thread(() -> {
            // ABA
            atomicReference.compareAndSet(100, 101);
            atomicReference.compareAndSet(101, 100);
            Integer i = atomicReference.get();
            System.out.println(Thread.currentThread().getName() + ": i = " + i);
        }).start();

        new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicReference.compareAndSet(100, 2020);
            Integer i = atomicReference.get();
            System.out.println(Thread.currentThread().getName() + ": i = " + i);
        }).start();

        while (Thread.activeCount() > 2) {
            // loop
        }

        Integer result = atomicReference.get();
        System.out.println("result = " + result);
    }
}
